/**
 * 研发项目数据结构迁移脚本
 * 将研发项目从旧字段格式迁移到新的小驼峰命名格式
 */

// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;
const MAX_LIMIT = 100;

// 集合名称
const COLLECTION_NAME = 'research_project';

// 字段映射表（旧字段名 => 新字段名）
const FIELD_MAPPING = {
  '_id': 'id',
  'PROJECT_CODE': 'projectCode',
  'PROJECT_NAME': 'projectName',
  'PROJECT_TITLE': 'projectTitle',
  'PROJECT_DESC': 'projectDesc',
  'PROJECT_CATE': 'projectType',
  'PROJECT_PRIORITY': 'priorityCode',
  'PROJECT_CUSTOMER_ID': 'customerId',
  'PROJECT_CUSTOMER_NAME': 'customerName',
  'PROJECT_CUSTOMER_CONTACT_NAME': 'customerContactName',
  'PROJECT_CUSTOMER_CONTACT_MOBILE': 'customerContactMobile',
  'PROJECT_MANAGER_ID': 'projectManagerId',
  'PROJECT_MANAGER_NAME': 'projectManagerName',
  'PROJECT_HARDWARE_OWNER_ID': 'hardwareOwnerId',
  'PROJECT_HARDWARE_OWNER_NAME': 'hardwareOwnerName',
  'PROJECT_SOFTWARE_OWNER_ID': 'softwareOwnerId',
  'PROJECT_SOFTWARE_OWNER_NAME': 'softwareOwnerName',
  'PROJECT_TEAM_MEMBER_IDS': 'teamMemberIds',
  'PROJECT_TEAM_MEMBER_NAMES': 'teamMemberNames',
  'PROJECT_TEAM_MEMBER_ROLES': 'teamMemberRoles',
  'STATUS_DESC': 'statusDesc',
  'STATUS_UPDATE_TIME': 'stateTime',
  'PROJECT_PROGRESS': 'progress',
  'PROJECT_START_DATE': 'startDate',
  'PROJECT_END_DATE': 'endDate',
  'PROJECT_PLAN_START_DATE': 'planStartDate',
  'PROJECT_PLAN_END_DATE': 'planEndDate',
  'CREATE_TIME': 'createTime',
  'UPDATE_TIME': 'updateTime',
  'ADD_TIME': 'createTime',
  'EDIT_TIME': 'updateTime',
  'work_temp': 'workTemp',
  'certification': 'certification',
  'low_power': 'lowPower',
  'startup_time': 'startupTime',
  'conformal_coating': 'conformalCoating',
  'rated_voltage': 'ratedVoltage',
  'max_power': 'maxPower',
  'max_speed': 'maxSpeed',
  'pole_pairs': 'polePairs',
  'has_hall': 'hasHall',
  'has_brake': 'hasBrake',
  'control_mode': 'controlMode',
  'control_algorithm': 'controlAlgorithm',
  'rotation': 'rotation',
  'control_interface': 'controlInterface',
  'pwm_start_duty': 'pwmStartDuty',
  'pwm_stop_duty': 'pwmStopDuty',
  'pwm_duty_range': 'pwmDutyRange',
  'pwm_freq_range': 'pwmFreqRange',
  'vsp_start_voltage': 'vspStartVoltage',
  'vsp_stop_voltage': 'vspStopVoltage',
  'vsp_voltage_range': 'vspVoltageRange',
  'stall_protection': 'stallProtection',
  'stall_hold_time': 'stallHoldTime',
  'stall_restart_time': 'stallRestartTime',
  'stall_restart_count': 'stallRestartCount',
  'overvoltage_protection': 'overvoltageProtection',
  'overvoltage_value': 'overvoltageValue',
  'overvoltage_recovery_value': 'overvoltageRecoveryValue',
  'undervoltage_protection': 'undervoltageProtection',
  'undervoltage_value': 'undervoltageValue',
  'undervoltage_recovery_value': 'undervoltageRecoveryValue',
  'temperature_protection': 'temperatureProtection',
  'protection_temp': 'protectionTemp',
  'recovery_temp': 'recoveryTemp',
  'overcurrent_protection': 'overcurrentProtection',
  'overcurrent_value': 'overcurrentValue',
  'current_limit_protection': 'currentLimitProtection',
  'current_limit_value': 'currentLimitValue',
  'blockage_protection': 'blockageProtection',
  'blockage_diameter': 'blockageDiameter',
  'blockage_hold_time': 'blockageHoldTime',
  'phase_protection': 'phaseProtection'
};

// 字段转换函数
function convertProject(oldProject) {
  const newProject = {};
  
  // 保留ID
  newProject._id = oldProject._id;
  
  // 保留level字段 (不改名)
  if (oldProject.level1 !== undefined) newProject.level1 = oldProject.level1;
  if (oldProject.level2 !== undefined) newProject.level2 = oldProject.level2;
  if (oldProject.level3 !== undefined) newProject.level3 = oldProject.level3;
  if (oldProject.level4 !== undefined) newProject.level4 = oldProject.level4;
  
  // 转换其他字段
  for (const oldField in oldProject) {
    if (oldField === '_id' || oldField.startsWith('level')) continue;
    
    if (FIELD_MAPPING[oldField]) {
      const newField = FIELD_MAPPING[oldField];
      
      // 避免重复的ADD_TIME和CREATE_TIME
      if (newField === 'createTime' && newProject.createTime !== undefined) continue;
      // 避免重复的EDIT_TIME和UPDATE_TIME
      if (newField === 'updateTime' && newProject.updateTime !== undefined) continue;
      
      newProject[newField] = oldProject[oldField];
    } else if (!oldField.startsWith('_')) {
      // 保留不在映射表中且不是内部字段的字段
      newProject[oldField] = oldProject[oldField];
    }
  }
  
  // 添加项目类型名称
  if (newProject.projectType !== undefined) {
    newProject.projectTypeName = getProjectTypeName(newProject.projectType);
  }
  
  // 确保必要的时间字段存在
  if (!newProject.createTime) newProject.createTime = Date.now();
  if (!newProject.updateTime) newProject.updateTime = Date.now();
  
  return newProject;
}

// 获取项目类型名称
function getProjectTypeName(cateId) {
  const cateMap = {
    0: '硬件项目',
    1: '软件项目',
    2: '综合项目',
    3: '研究项目',
    4: '其他项目'
  };
  return cateMap[cateId] || '未知类型';
}

// 分批获取所有项目
async function getAllProjects() {
  // 查询项目总数
  const countResult = await db.collection(COLLECTION_NAME).count();
  const total = countResult.total;
  
  // 计算需要分几次取
  const batchTimes = Math.ceil(total / MAX_LIMIT);
  
  // 分批获取数据
  const tasks = [];
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection(COLLECTION_NAME)
      .skip(i * MAX_LIMIT)
      .limit(MAX_LIMIT)
      .get();
    tasks.push(promise);
  }
  
  // 等待所有批次完成
  const results = await Promise.all(tasks);
  let projects = [];
  
  // 合并结果
  results.forEach(result => {
    projects = projects.concat(result.data);
  });
  
  return projects;
}

// 更新项目数据
async function updateProject(oldId, newProject) {
  try {
    await db.collection(COLLECTION_NAME).doc(oldId).update({
      data: newProject
    });
    return true;
  } catch (e) {
    console.error(`Failed to update project ${oldId}:`, e);
    return false;
  }
}

// 主函数
exports.main = async (event, context) => {
  try {
    // 获取所有项目
    const projects = await getAllProjects();
    console.log(`Found ${projects.length} projects to migrate`);
    
    // 转换和更新
    const results = [];
    
    for (const project of projects) {
      const newProject = convertProject(project);
      const oldId = project._id;
      
      // 删除_id，避免更新冲突
      delete newProject._id;
      
      // 更新项目
      const success = await updateProject(oldId, newProject);
      results.push({
        id: oldId,
        success,
        oldFields: Object.keys(project).length,
        newFields: Object.keys(newProject).length
      });
    }
    
    return {
      success: true,
      total: projects.length,
      results
    };
  } catch (error) {
    console.error('Migration failed:', error);
    return {
      success: false,
      error: error.message
    };
  }
}; 